package com.yx.changdao.web.config.shiro.filter;

import com.yx.changdao.common.data.RespCodeEnum;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.SysUser;
import com.yx.changdao.common.utils.JwtUtils;
import com.yx.changdao.common.utils.SysConst;
import com.yx.changdao.service.SysUserService;
import com.yx.changdao.web.config.shiro.token.JwtToken;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * Jwt 的过滤器
 */
public class JwtAuthFilter extends AuthenticatingFilter {

    // 刷新token的间隔时间
    private static final int tokenRefreshInterval = 3000;

    // 用户服务
    private SysUserService userService;


    public JwtAuthFilter(SysUserService userService) {
        // 默认的登录地址
//        this.setLoginUrl("");
        this.userService = userService;
    }

    /**
     * 拦截器: 前置处理方法
     * 对于OPTION请求做拦截，不做token校验
     *
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        // 对于OPTION请求做拦截，不做token校验
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return false;
        }

        return super.preHandle(request, response);
    }

    /**
     * 后置处理方法
     *
     * @return
     * @throws Exception
     */
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) {
        this.fillCorsHeader(WebUtils.toHttp(request), WebUtils.toHttp(response));
        request.setAttribute(SysConst.SHIRO_STARTUS_FILTERED, true);
    }

    /**
     * 从AuthenticatingFilter继承，重写isAccessAllow方法，方法中调用父类executeLogin()。
     * 父类的这个方法首先会createToken()，然后调用shiro的Subject.login()方法。
     * 父类会在请求进入拦截器后调用该方法，返回true则继续，返回false则会调用onAccessDenied()。
     * 这里在不通过时，还调用了isPermissive()方法。
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (this.isLoginRequest(request, response)) {
            return true;
        }
        Boolean afterFiltered = (Boolean) (request.getAttribute(SysConst.SHIRO_STARTUS_FILTERED));
        if (BooleanUtils.isTrue(afterFiltered)) {
            return true;
        }
        boolean allowed = false;
        try {
            allowed = executeLogin(request, response);
        } catch (IllegalStateException e) {
            System.out.println("Not found any token");
//            throw new RuntimeException("Not found any token",e);
            //not found any token

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error occurs when login" + e);
//            throw new RuntimeException("Error occurs when login",e);
        }
        return allowed || super.isPermissive(mappedValue);
    }

    /**
     * 这里重写了父类的方法，使用我们自己定义的Token类，提交给shiro。
     * 这个方法返回null的话会直接抛出异常，进入isAccessAllowed（）的异常处理逻辑。
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String jwtToken = getAuthzHeader(servletRequest);
        if (StringUtils.isNotBlank(jwtToken) && !JwtUtils.isTokenExpired(jwtToken)) {
            return new JwtToken(jwtToken);
        }
        return null;
    }

    /**
     * 如果这个Filter在之前isAccessAllowed（）方法中返回false,则会进入这个方法。我们这里直接返回错误的response
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
//        LOGGER.debug("Authentication required: sending 401 Authentication challenge response.");
        HttpServletResponse httpResponse = WebUtils.toHttp(servletResponse);

        HttpServletRequest httpServletRequest = WebUtils.toHttp(servletRequest);
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json; charset=utf-8");

        httpResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        httpResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));


        final String message = "请重新登录";
        try (PrintWriter out = httpResponse.getWriter()) {
            String responseJson = Json.toJson(Result.error(RespCodeEnum.UNAUTHORIZED, message), JsonFormat.compact());
            out.print(responseJson);
            out.close();
        } catch (IOException e) {
//            LOGGER.error("sendChallenge error：", e);
            System.out.println(e);
        }
        return false;

    }

    /**
     * 如果Shiro Login认证成功，会进入该方法，等同于用户名密码登录成功，我们这里还判断了是否要刷新Token
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
       /* HttpServletResponse httpResponse = WebUtils.toHttp(response);
        String newToken = null;
        if (token instanceof JwtToken) {
            JwtToken jwtToken = (JwtToken) token;
            SysUser user = (SysUser) subject.getPrincipal();
            // 判断是否刷新token
            boolean shouldRefresh = shouldTokenRefresh(JwtUtils.getIssuedAt(jwtToken.getToken()));
            // 刷新token
            if (shouldRefresh) {
                newToken = userService.generateJwtToken(user);
            }
        }

        if (StringUtils.isNotBlank(newToken)) {
            // 将token响应头
            httpResponse.setHeader(SysConst.HEAD_TOKEN, newToken);
        }*/
        return true;
    }

    /**
     * 如果调用shiro的login认证失败，会回调这个方法，这里我们什么都不做，因为逻辑放到了onAccessDenied（）中。
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        return false;
    }

    /**
     * 获取请求头中token
     *
     * @param request
     * @return
     */
    protected String getAuthzHeader(ServletRequest request) {
//        HttpServletRequest httpRequest = WebUtils.toHttp(request);
//        String header = httpRequest.getHeader(SysConst.HEAD_TOKEN);
//        return StringUtils.removeStart(header, "Bearer ");

        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        return httpRequest.getHeader(SysConst.HEAD_TOKEN);
    }

    /**
     * 是否刷新token
     *
     * @param issueAt
     * @return
     */
    protected boolean shouldTokenRefresh(Date issueAt) {
        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
        return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
    }

    /**
     * 设置跨域请求
     *
     * @param httpServletRequest
     * @param httpServletResponse
     */
    protected void fillCorsHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
    }
}
